<?php

namespace App\Console\Commands\Hand;

use App\Library\MakeFile\BaseMakeFile;
use App\Library\MakeFile\ControllerMakeFile;
use App\Library\MakeFile\ExceptionsMakeFile;
use App\Library\MakeFile\ModelMakeFile;
use App\Library\MakeFile\ServiceMakeFile;
use App\Library\MakeFile\ValidateMakeFile;
use App\Library\MakeFile\EnumMakeFile;
use Illuminate\Console\Command;

class AddModule extends Command
{
    /**
     * codePrefix 参考下面链接
     * @link https://onepiece-group.feishu.cn/docs/doccn0yxNVLk7dLrAhLTxDX8Jdb
     * @var string
     */
    protected $signature = 'add:module {module} {codePrefix} {clientName}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动生成模块';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    private $classList = [
        'Controller' => ControllerMakeFile::class,
        'Service'    => ServiceMakeFile::class,
        'Validate'   => ValidateMakeFile::class,
        'Enum'       => EnumMakeFile::class,
        'Exceptions' => ExceptionsMakeFile::class,
        'Model'      => ModelMakeFile::class,
    ];

    public function handle()
    {
        $module     = ucfirst($this->argument('module')); // 模块名 User、Product...
        $codePrefix = (int)$this->argument('codePrefix'); // 错误码前缀401、402...
        $clientName = ucfirst($this->argument('clientName')); // 端名 B、Pos...

        if (!$codePrefix) {
            dd('请输入错误码前缀');
        }

        if ($codePrefix < 401 || $codePrefix > 999) {
            dd('错误码前缀必须介于[401, 999]');
        }

        if (!isset(BaseMakeFile::CLIENT_ENUM[$clientName])) {
            dd('错误的clientName,仅支持:' . json_encode(array_keys(BaseMakeFile::CLIENT_ENUM)));
        }


        // 生成模块
        foreach ($this->classList as $className => $class) {
            (new $class($module, $className, $codePrefix))->setClientName($clientName)->doModule();
        }

        // 生成路由
        (new BaseMakeFile($module, 'Router', 0))->doRouter($clientName);
    }
}
